package com.bwie.server;

import javax.annotation.PostConstruct;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

@Slf4j
@Component
public class NettyTcpServer {
    private final int port = 9000;

    @PostConstruct
    public void start() {
        new Thread(() -> {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) {
                                ChannelPipeline p = ch.pipeline();
                                p.addLast(new LineBasedFrameDecoder(1024));
                                p.addLast(new StringDecoder(CharsetUtil.UTF_8));
                                p.addLast(new StringEncoder(CharsetUtil.UTF_8));

                            }
                        });
                ChannelFuture sync = bootstrap.bind(9500).sync();
                sync.channel().closeFuture().sync();
                log.info("---------------- 启动了一个 netty 线程");

//                ChannelFuture f = bootstrap.bind(port).sync();
//                System.out.println("服务器在端口上启动" + port);
//                f.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.error("---------------- netty 线程 异常：" + e.getMessage());
            }
//            finally {
//                bossGroup.shutdownGracefully();
//                workerGroup.shutdownGracefully();
//            }
        }).start();
    }

}
